const express = require('express')
const cors = require('cors')
const { expressjwt } = require('express-jwt')
const app = express()
const handleError = require('./utils/handleError.js')
const loginRouter = require('./router/login')
const fileRouter = require('./router/file.js')
const connectRouter = require('./router/connect.js')
const chatRouter = require('./router/chat.js')
const settingRouter = require('./router/setting.js')
const searchRouter = require('./router/search.js')

// app.use(cors())

// 解析 token 的中间件 (以 /login 开头的 以及 下载头像的 不需要检验 token)
const secretKey = 'isomer 1229 ^.^'
app.use(expressjwt({ secret: secretKey, algorithms: ['HS256'] }).unless({ path: [/^\/login\//,  /^\/setting\/download\/avatar/] }))

// 配置解析表单数据的中间件
app.use(express.urlencoded({ extended: false }))
app.use(express.json())

// 错误处理中间件
app.use(handleError)

app.use('/login', loginRouter)
app.use('/file', fileRouter)
app.use('/connect', connectRouter)
app.use('/chat', chatRouter)
app.use('/setting', settingRouter)
app.use('/search', searchRouter)

const port = 9091
app.listen(port, () => {
  console.log(`Server is running on port ${port}`)
})

const WebSocketService = require('./service/websocket_service.js')
// 开启服务端对客户端的连接监听
WebSocketService.listen()
